package library;

import java.util.*;
import utils.ResourceFileUtils;

public class Library {
    private Map<String, Resource> resources;
    private Map<String, Borrower> borrowers;

    public Library() {
        this.resources = new HashMap<>();
        this.borrowers = new HashMap<>();

        List<Resource> loadedResources = ResourceFileUtils.loadResources();
        for (Resource r : loadedResources) {
            resources.put(r.getId(), r);
        }

        Map<String, List<String>> borrowRecords = ResourceFileUtils.loadBorrowRecords();
        for (Map.Entry<String, List<String>> entry : borrowRecords.entrySet()) {
            String borrowerName = entry.getKey();
            List<String> resourceIds = entry.getValue();

            Borrower borrower = new Borrower(borrowerName);
            for (String id : resourceIds) {
                Resource r = resources.get(id);
                if (r != null && !r.isAvailable()) {
                    try {
                        r.getClass().getMethod("borrow").invoke(r);
                    } catch (Exception ignored) {}
                    borrower.getBorrowedResources().add(r);
                }
            }
            borrowers.put(borrowerName, borrower);
        }

        if (loadedResources.isEmpty()) {
            saveResourcesToFile();
        }
    }

    private void addDefaultResources() {
        addResource(new Book("B001", "Java编程思想"));
        addResource(new Magazine("M001", "读者文摘"));
        addResource(new DVD("D001", "电影光盘"));
    }

    public void addResource(Resource resource) {
        resources.put(resource.getId(), resource);
        saveResourcesToFile();
    }

    public void removeResource(String id) {
        resources.remove(id);
        saveResourcesToFile();
    }

    public Collection<Resource> getAllResources() {
        return resources.values();
    }

    public Resource findResourceById(String id) {
        return resources.get(id);
    }

    public void addBorrower(Borrower borrower) {
        borrowers.put(borrower.getName(), borrower);
        saveResourcesToFile();
    }

    public Borrower getBorrower(String name) {
        return borrowers.get(name);
    }

    public void saveResourcesToFile() {
        List<Resource> resourceList = new ArrayList<>(resources.values());
        ResourceFileUtils.saveResources(resourceList);
        ResourceFileUtils.saveBorrowRecords(borrowers);
    }
}